import axios from 'axios'
import {getItem} from "@/utils/SystemUtil";

const timeout: number = 15000;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
export function formatError(status: number) {
    if (status == 401) {
        return Promise.resolve({
            code: status,
            message: '登陆过期,重新登录!'
        })
    } else if (status == 404) {
        return {
            code: status,
            message: '访问资源不存在!'
        };
    } else if (status == 500) {
        return {
            code: status,
            message: '服务器内部错误!'
        }
    } else if (status == 503) {
        return {
            code: status,
            message: '服务器不可用!'
        }
    } else if (status != 200) {
        return Promise.resolve({
            code: status,
            message: '服务器忙，请稍后再试!'
        })
    }
}

// axios对象
const service = axios.create({
    // axios请求基础URL
    // 由于本项目使用mock + vite-plugin-mock启动的mock服务，默认使用的端口号与页面一致
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: timeout
})

// 设置请求拦截器
service.interceptors.request.use(
    (config) => {
        // 添加请求头参数
        const masterToken: any = getItem('UNI_MASTER_SESSION_ID');
        if (masterToken) {
            config.headers['UNI_MASTER_SESSION_ID'] = masterToken;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error)
    }
)
// 设置响应拦截器
service.interceptors.response.use(
    (res) => {
        return res;
    },
    (error) => {
        error.response.data = formatError(error.response.status);
        return Promise.resolve(error.response);
    }
)

export default service;
